package com.itcj.dmp.utils

import com.typesafe.config.ConfigFactory
import okhttp3._
import org.json4s
import org.json4s.{DefaultFormats, Formats, JValue, JsonMethods, JsonUtil, StringInput}
import org.json4s.jackson.{Json, JsonMethods}

object HttpUtils {
    val conf=ConfigFactory.load("url")
    val key=conf.getString("key")
    val baseurl=conf.getString("baseurl")


    val client=new OkHttpClient

    def getLocationInf(longitude: Double, latitude: Double): Option[String] = {
      val url = s"$baseurl$longitude,$latitude&key=$key"
      try {
        val request = new Request.Builder().url(url).build()

        val response: Response = client.newCall(request).execute()
        if (response.isSuccessful) {
          val result = response.body().string()
          Some(result)
        }
        else {
          None
        }
      } catch {
        case e: Exception => {
          e.printStackTrace()
          None
        }
      }
    }


  def jsonParse(jsonInfo:String):String={
     val jvalue: JValue = JsonMethods.parse(StringInput(jsonInfo))
    val bajvalue: List[JValue] = jvalue.\\("businessAreas").children
    var str=""
    for(value <- bajvalue) {
      val jValue1 = value.\("name")
      str+=jValue1.values+","
    }
    str=str.substring(0,str.length-1)
    str
  }

 def jsonProcess(longitude: Double, latitude: Double):String={
   val str: Option[String] = getLocationInf(longitude,latitude)
//   println(str.getOrElse("000"))
   if(str.isEmpty) {
     return ""
   }

   val str1: String = jsonParse(str.get)
   if(str1=="None") {
//     println(111)
     return null
   }
   str1
 }
}



